﻿using System;
using System.Data.SqlClient;
using System.Reflection;
using System.Text;

namespace DataBroker.Dal
{
    ///<summary>
    ///</summary>
    public class D2BkUOW
    {
        private ICloneable[] _ObjList;
        private MethodBase _Method;

        ///<summary>
        ///</summary>
        ///<param name="method"></param>
        ///<param name="args"></param>
        public D2BkUOW(MethodBase method, ICloneable[] args)
        {
            _Method = method;
            _ObjList = new ICloneable[args.Length];
            for (int i = 0; i < args.Length; i++)
            {
                _ObjList[i] = (ICloneable)args[i].Clone();
            }
        }

        ///<summary>
        ///</summary>
        ///<returns></returns>
        public object Execute()
        {
            object result = null;
            StringBuilder sb = new StringBuilder();
            ICloneable[] args = new ICloneable[_ObjList.Length];
            for (int i = 0; i < _ObjList.Length; i++)
            {
                args[i] = (ICloneable)_ObjList[i].Clone();
                sb.AppendFormat("{0} = {1}", _ObjList[i].GetType(), _ObjList[i]);
            }
            try
            {
                D2Bk.LogDebug("Invoking {0} with parameters {1}", _Method.Name, sb);
                result = _Method.Invoke(null, args);
            }
            catch (TargetInvocationException ex)
            {
                D2Bk.LogError("Exception invoking {0} with parameters {1}: {2}", _Method.Name, sb, ex.Message);
                if (ex.InnerException != null)
                {
                    D2Bk.LogError("Inner Exception {0}, {1}", ex.InnerException.Message, ex.InnerException.StackTrace);
                    if (ex.InnerException.GetType() == typeof(SqlException))
                    {
                        return ex.InnerException;
                    }
                }
            }
            catch (SqlException sqlex)
            {
                return sqlex;
            }
            return result;
        }
    }
}